<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 页面标题 -->
    <div class="bg-white border-b border-gray-200 shadow-sm">
      <div class="container mx-auto px-4 py-5">
        <h1 class="text-2xl font-bold text-gray-800">关键词生成栏目</h1>
        <p class="text-gray-500 mt-1">通过核心关键词自动生成相关栏目结构和子主题</p>
      </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="container mx-auto px-4 py-6">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 左侧：参数设置 -->
        <div class="lg:col-span-1">
          <div class="bg-white rounded-lg shadow-sm p-5 sticky top-4">
            <h2 class="text-lg font-medium text-gray-800 mb-4">生成参数</h2>
            
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">核心关键词</label>
                <input
                  type="text"
                  v-model="form.keyword"
                  class="form-input w-full"
                  placeholder="输入核心主题关键词"
                >
                <p class="text-xs text-gray-500 mt-1">例如：人工智能、健康养生、旅游攻略</p>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">栏目层级</label>
                <select
                  v-model="form.level"
                  class="form-input w-full"
                >
                  <option value="1">一级栏目 (仅主栏目)</option>
                  <option value="2" selected>二级栏目 (主栏目+子栏目)</option>
                  <option value="3">三级栏目 (主栏目+子栏目+孙栏目)</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">每个层级数量</label>
                <select
                  v-model="form.count"
                  class="form-input w-full"
                >
                  <option value="3">3个/层级</option>
                  <option value="5" selected>5个/层级</option>
                  <option value="7">7个/层级</option>
                  <option value="10">10个/层级</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">内容方向</label>
                <select
                  v-model="form.direction"
                  class="form-input w-full"
                >
                  <option value="general" selected>综合全面</option>
                  <option value="professional">专业深度</option>
                  <option value="popular">通俗普及</option>
                  <option value="practical">实用指南</option>
                  <option value="news">新闻资讯</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">额外要求</label>
                <textarea
                  v-model="form.requirements"
                  class="form-input w-full min-h-[100px]"
                  placeholder="输入其他特殊要求或说明..."
                ></textarea>
              </div>
              
              <div class="pt-2">
                <button
                  class="btn btn-primary w-full flex items-center justify-center"
                  :disabled="loading || !form.keyword"
                  @click="generateCategories"
                >
                  <i v-if="loading" class="fa fa-spinner fa-spin mr-2"></i>
                  <span>生成栏目</span>
                </button>
                <button
                  class="btn btn-secondary w-full mt-3"
                  @click="clearForm"
                >
                  重置参数
                </button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 右侧：生成结果 -->
        <div class="lg:col-span-2">
          <div class="bg-white rounded-lg shadow-sm overflow-hidden">
            <!-- 结果工具栏 -->
            <div class="bg-gray-50 px-5 py-3 border-b border-gray-200 flex flex-wrap items-center justify-between gap-3">
              <h2 class="text-lg font-medium text-gray-800">栏目结构</h2>
              
              <div class="flex gap-2">
                <button
                  class="btn btn-secondary flex items-center"
                  :disabled="!categories.length"
                  @click="copyToClipboard"
                >
                  <i class="fa fa-copy mr-1"></i>复制
                </button>
                <button
                  class="btn btn-secondary flex items-center"
                  :disabled="!categories.length"
                  @click="downloadCategories"
                >
                  <i class="fa fa-download mr-1"></i>下载
                </button>
                <button
                  class="btn btn-primary flex items-center"
                  :disabled="!categories.length || loading"
                  @click="regenerateCategories"
                >
                  <i v-if="loading" class="fa fa-spinner fa-spin mr-1"></i>
                  <i v-else class="fa fa-refresh mr-1"></i>
                  重新生成
                </button>
              </div>
            </div>
            
            <!-- 结果内容区 -->
            <div class="p-5">
              <!-- 空状态 -->
              <div v-if="!categories.length && !loading" class="py-16 text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                  <i class="fa fa-sitemap text-2xl text-gray-400"></i>
                </div>
                <h3 class="text-lg font-medium mb-2">尚未生成栏目</h3>
                <p class="text-gray-500 max-w-md mx-auto">
                  输入核心关键词并设置参数，AI将为您生成相关的栏目结构
                </p>
              </div>
              
              <!-- 加载状态 -->
              <div v-if="loading" class="py-16 text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                  <i class="fa fa-spinner fa-spin text-2xl text-primary"></i>
                </div>
                <h3 class="text-lg font-medium mb-2">AI正在生成栏目结构</h3>
                <p class="text-gray-500 max-w-md mx-auto">
                  请稍候，AI正在分析关键词并创建相关栏目...
                </p>
              </div>
              
              <!-- 生成结果 -->
              <div v-if="categories.length && !loading">
                <div class="flex items-center text-sm text-gray-500 mb-6">
                  <span><i class="fa fa-clock-o mr-1"></i> 生成时间: {{ generateTime }}</span>
                  <span class="mx-3">|</span>
                  <span><i class="fa fa-folder-open-o mr-1"></i> 总栏目数: {{ totalCategoryCount }}</span>
                </div>
                
                <!-- 栏目树形结构 -->
                <div class="category-tree">
                  <ul class="list-none pl-0">
                    <li v-for="(category, index) in categories" :key="index" class="mb-4">
                      <div class="flex items-center p-3 bg-gray-50 rounded-lg border border-gray-200">
                        <i class="fa fa-folder text-primary mr-3"></i>
                        <span class="font-medium">{{ category.name }}</span>
                        <span class="ml-2 text-xs px-2 py-0.5 bg-gray-200 rounded-full text-gray-700">
                          {{ category.subCategories.length }}个子栏目
                        </span>
                        <button 
                          class="ml-auto text-gray-400 hover:text-primary"
                          @click="category.expanded = !category.expanded"
                        >
                          <i class="fa" :class="category.expanded ? 'fa-chevron-up' : 'fa-chevron-down'"></i>
                        </button>
                      </div>
                      
                      <!-- 二级栏目 -->
                      <ul v-if="form.level >= 2 && category.expanded" class="list-none pl-6 mt-2">
                        <li v-for="(subCat, subIndex) in category.subCategories" :key="subIndex" class="mb-3">
                          <div class="flex items-center p-2 bg-gray-50 rounded-lg border border-gray-200">
                            <i class="fa fa-folder-open text-primary mr-3"></i>
                            <span>{{ subCat.name }}</span>
                            <span v-if="form.level >= 3" class="ml-2 text-xs px-2 py-0.5 bg-gray-200 rounded-full text-gray-700">
                              {{ subCat.subCategories.length }}个子栏目
                            </span>
                            <button 
                              v-if="form.level >= 3"
                              class="ml-auto text-gray-400 hover:text-primary"
                              @click="subCat.expanded = !subCat.expanded"
                            >
                              <i class="fa" :class="subCat.expanded ? 'fa-chevron-up' : 'fa-chevron-down'"></i>
                            </button>
                          </div>
                          
                          <!-- 三级栏目 -->
                          <ul v-if="form.level >= 3 && subCat.expanded" class="list-none pl-6 mt-2">
                            <li v-for="(subSubCat, subSubIndex) in subCat.subCategories" :key="subSubIndex" class="mb-2">
                              <div class="flex items-center p-2 bg-gray-50 rounded-lg border border-gray-200">
                                <i class="fa fa-file-o text-primary mr-3"></i>
                                <span>{{ subSubCat.name }}</span>
                              </div>
                            </li>
                          </ul>
                        </li>
                      </ul>
                    </li>
                  </ul>
                </div>
                
                <!-- 栏目说明 -->
                <div class="mt-8 p-4 bg-blue-50 border border-blue-100 rounded-lg">
                  <h3 class="font-medium text-blue-800 mb-2 flex items-center">
                    <i class="fa fa-info-circle mr-2"></i>栏目使用建议
                  </h3>
                  <ul class="list-disc pl-5 text-sm text-blue-700 space-y-1">
                    <li>可根据实际需求调整栏目名称和层级结构</li>
                    <li>二级和三级栏目可作为内容创作的具体方向</li>
                    <li>可结合AI文章生成工具，为每个栏目创建内容</li>
                    <li>建议保留相关性最高的栏目，删除不相关的分类</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 历史记录 -->
          <div class="bg-white rounded-lg shadow-sm mt-6">
            <div class="px-5 py-3 border-b border-gray-200">
              <h2 class="text-lg font-medium text-gray-800">生成历史</h2>
            </div>
            <div class="p-0">
              <div 
                v-for="(history, index) in generateHistory" 
                :key="index"
                class="px-5 py-3 border-b border-gray-100 hover:bg-gray-50 cursor-pointer transition-colors"
                @click="loadHistory(history)"
              >
                <div class="font-medium text-gray-800 truncate">关键词: {{ history.keyword }}</div>
                <div class="flex items-center justify-between mt-1">
                  <span class="text-xs text-gray-500">{{ formatHistoryTime(history.timestamp) }}</span>
                  <span class="text-xs text-gray-500">{{ history.totalCount }} 个栏目</span>
                </div>
              </div>
              
              <div v-if="generateHistory.length === 0" class="px-5 py-8 text-center text-gray-500 text-sm">
                暂无生成历史
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { formatDate } from '@/utils/date'

// 表单数据
const form = ref({
  keyword: '',
  level: '2',
  count: '5',
  direction: 'general',
  requirements: ''
})

// 生成状态
const loading = ref(false)
const categories = ref([])
const generateTime = ref('')
const generateHistory = ref([])

// 计算总栏目数
const totalCategoryCount = computed(() => {
  let count = categories.value.length
  
  // 加上二级栏目
  categories.value.forEach(cat => {
    count += cat.subCategories.length
    
    // 加上三级栏目
    cat.subCategories.forEach(subCat => {
      count += subCat.subCategories.length
    })
  })
  
  return count
})

// 生成栏目
const generateCategories = async () => {
  if (!form.value.keyword) return
  
  loading.value = true
  try {
    // 模拟AI生成过程
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    const result = []
    const count = parseInt(form.value.count)
    const level = parseInt(form.value.level)
    
    // 生成一级栏目
    for (let i = 0; i < count; i++) {
      const firstLevel = generateCategoryName(form.value.keyword, 1, i)
      
      const secondLevelCats = []
      // 生成二级栏目
      if (level >= 2) {
        for (let j = 0; j < count; j++) {
          const secondLevel = generateCategoryName(firstLevel, 2, j)
          
          const thirdLevelCats = []
          // 生成三级栏目
          if (level >= 3) {
            for (let k = 0; k < count; k++) {
              thirdLevelCats.push({
                name: generateCategoryName(secondLevel, 3, k),
                expanded: false
              })
            }
          }
          
          secondLevelCats.push({
            name: secondLevel,
            subCategories: thirdLevelCats,
            expanded: false
          })
        }
      }
      
      result.push({
        name: firstLevel,
        subCategories: secondLevelCats,
        expanded: true
      })
    }
    
    // 更新结果
    categories.value = result
    generateTime.value = new Date().toLocaleString()
    
    // 保存到历史记录
    saveToHistory()
    
  } catch (error) {
    console.error('生成栏目失败:', error)
  } finally {
    loading.value = false
  }
}

// 重新生成栏目
const regenerateCategories = () => {
  generateCategories()
}

// 生成栏目名称（模拟AI生成）
const generateCategoryName = (parentKeyword, level, index) => {
  // 一级栏目前缀
  const level1Prefixes = [
    '基础', '进阶', '高级', '入门', '核心', 
    '最新', '热门', '经典', '实用', '理论'
  ]
  
  // 二级栏目前缀
  const level2Prefixes = [
    '概念', '原理', '技术', '方法', '工具',
    '案例', '教程', '指南', '技巧', '策略'
  ]
  
  // 三级栏目后缀
  const level3Suffixes = [
    '详解', '分析', '实践', '应用', '解读',
    '教程', '实例', '指南', '技巧', '误区'
  ]
  
  // 修饰词
  const modifiers = [
    '全面的', '深入的', '实用的', '高效的', '创新的',
    '专业的', '通俗的', '最新的', '经典的', '必备的'
  ]
  
  let name = ''
  const keyword = parentKeyword.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '')
  
  if (level === 1) {
    // 一级栏目
    const prefix = level1Prefixes[index % level1Prefixes.length]
    name = `${prefix}${keyword}`
  } else if (level === 2) {
    // 二级栏目
    const prefix = level2Prefixes[index % level2Prefixes.length]
    name = `${keyword}${prefix}`
  } else if (level === 3) {
    // 三级栏目
    const suffix = level3Suffixes[index % level3Suffixes.length]
    const modifier = modifiers[Math.floor(Math.random() * modifiers.length)]
    name = `${modifier}${keyword}${suffix}`
  }
  
  return name
}

// 保存到历史记录
const saveToHistory = () => {
  const historyItem = {
    keyword: form.value.keyword,
    categories: categories.value,
    timestamp: new Date().getTime(),
    totalCount: totalCategoryCount.value,
    params: { ...form.value }
  }
  
  generateHistory.value.unshift(historyItem)
  
  // 限制历史记录数量
  if (generateHistory.value.length > 10) {
    generateHistory.value.pop()
  }
}

// 加载历史记录
const loadHistory = (history) => {
  categories.value = history.categories
  generateTime.value = new Date(history.timestamp).toLocaleString()
  form.value = { ...history.params }
}

// 格式化历史时间
const formatHistoryTime = (timestamp) => {
  return formatDate(new Date(timestamp), 'yyyy-MM-dd HH:mm')
}

// 复制到剪贴板
const copyToClipboard = () => {
  if (!categories.value.length) return
  
  // 构建文本格式
  let text = `基于关键词"${form.value.keyword}"的栏目结构：\n\n`
  
  categories.value.forEach((cat, index) => {
    text += `${index + 1}. ${cat.name}\n`
    
    cat.subCategories.forEach((subCat, subIndex) => {
      text += `  ${index + 1}.${subIndex + 1}. ${subCat.name}\n`
      
      subCat.subCategories.forEach((subSubCat, subSubIndex) => {
        text += `    ${index + 1}.${subIndex + 1}.${subSubIndex + 1}. ${subSubCat.name}\n`
      })
    })
  })
  
  navigator.clipboard.writeText(text)
    .then(() => {
      alert('栏目结构已复制到剪贴板')
    })
    .catch(err => {
      console.error('复制失败:', err)
    })
}

// 下载栏目结构
const downloadCategories = () => {
  if (!categories.value.length) return
  
  // 构建文本内容
  let text = `基于关键词"${form.value.keyword}"的栏目结构：\n\n`
  
  categories.value.forEach((cat, index) => {
    text += `${index + 1}. ${cat.name}\n`
    
    cat.subCategories.forEach((subCat, subIndex) => {
      text += `  ${index + 1}.${subIndex + 1}. ${subCat.name}\n`
      
      subCat.subCategories.forEach((subSubCat, subSubIndex) => {
        text += `    ${index + 1}.${subIndex + 1}.${subSubIndex + 1}. ${subSubCat.name}\n`
      })
    })
  })
  
  const blob = new Blob([text], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${form.value.keyword}_栏目结构.txt`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

// 清空表单
const clearForm = () => {
  form.value = {
    keyword: '',
    level: '2',
    count: '5',
    direction: 'general',
    requirements: ''
  }
}
</script>
